import { Service } from '../../services/service'
import { formaturl } from '@/utils/commonUtils'
const state = {
  uploadHeader: {},
  shelveUrlsMapping: {
    1: '/hanyun/app-service/api/v1/app/add',
    2: '/hanyun/app-service/api/v1/service/add',
    3: '/hanyun/app-service/api/v1/model/add'
  },
  updateUrlMapping: {
    1: '/hanyun/app-service/api/v1/app/update',
    2: '/hanyun/app-service/api/v1/service/update',
    3: '/hanyun/app-service/api/v1/app/update'
  },
  filterReqIdMapping: {
    1: 1,
    2: 0,
    3: 2
  },
  filterUrl: '/hanyun/app-service/api/v1/open/type/query',
  editType: '1'
}
const getters = {}
const mutations = {
  setUploadHeader(state, data) {
    state.uploadHeader = data
  },
  setFilterData(state, data) {
    data.data.forEach((item) => {
      item.label = item.name
      item.value = item.id
      if (data.type === '1' || data.type === '3') {
        item.leaf = true
      } else {
        item.leaf = item.parentId !== '-1'
      }
    })
    state.filterData = data.data
  },
  setEditType(state, type) {
    state.editType = type
  }
}
const actions = {
  async shelveGoods({ state }, shelveParams) {
    const ret = await Service({
      url: state.shelveUrlsMapping[shelveParams.type],
      method: 'post',
      data: {
        ...shelveParams.params
      }
    })
    return new Promise((resolve, reject) => {
      if (ret.status === 200) {
        resolve('上架成功')
      } else {
        reject(ret.msg)
      }
    })
  },
  async updateShelvesGoods({ state }, updateInfo) {
    const res = await Service({
      url: state.updateUrlMapping[updateInfo.type],
      method: 'post',
      data: { ...updateInfo.params }
    })
    return new Promise((resolve, reject) => {
      if (res.status === 200) {
        resolve('更新成功')
      } else {
        reject(res.msg)
      }
    })
  },
  async getFilters({ commit, state }, params = {}) {
    const ret = await Service({
      url:
        state.filterUrl +
        formaturl({
          category: state.filterReqIdMapping[params.type],
          ...params.params
        }),
      method: 'get'
    })
    return new Promise((resolve) => {
      if (ret.status === 200) {
        commit('setFilterData', { data: ret.result, type: params.type })
        resolve(ret.result)
      }
    })
  }
}
export default {
  namespaced: true,
  state,
  getters,
  mutations,
  actions
}
